package com.ruoyi.wechat.api;



import com.ruoyi.common.annotation.Anonymous;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

//@Anonymous
@RestController
@RequestMapping("/wechat")
public class QRCodeController {

    @Autowired
    private QRCodeGenerator qrCodeGenerator;

    @Anonymous
    @GetMapping("/generateQRCode/{text}")
    public ResponseEntity<byte[]> generateQRCode(@PathVariable String text) {

        System.out.println("text: "+text);

        try {
            byte[] qrCodeImage = qrCodeGenerator.generateQRCodeImage(text);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(qrCodeImage, headers, HttpStatus.OK);
//            System.out.println("responseEntity: "+responseEntity.getBody());
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/generateQRCodeImage")
    public void generateQRCodeImage(HttpServletResponse response, @RequestParam String text) {
        try {
            qrCodeGenerator.generateQRCodeToResponse(response, text);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
